package com.training2.bookstore.product.controller;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.training2.bookstore.order.controller.LogService;
import com.training2.bookstore.product.model.Product;
import com.training2.bookstore.product.service.ProductService;
import com.training2.bookstore.product.service.StorageService;

@RestController()
@RequestMapping("/product")
public class ProductController {
	@Autowired LogService logService;
	@Autowired StorageService service ;
	@Autowired ApplicationContext context;
	
	ProductService getProductService() {
		
		ProductService productService = context.getBean(ProductService.class);
		return productService;
	}
	
	
	
	@GetMapping("/list")
	public Collection<Product> list(HttpServletRequest req) 
	{
//		logService.logIt(req, "product.create", "product/list");
		
		return getProductService() .listProduct();

	}
	@PostMapping("/add")
	public Product create(@RequestBody Product p) {
		
		return getProductService() .create(p);
	}
	
	@GetMapping("/update")
	public Product update(Product p) {
		return getProductService() .update(p);
	
	}
	@GetMapping("/remove")
	public Product remove(String id) {
		return getProductService().remove(id);
		
	}
	@PostMapping(value = "/uploadImage", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	public String uploadImage(@RequestParam("file") MultipartFile file, String productId) {
			if (file.isEmpty()) {
				return null;
			}
			String storedFileId = service.store(file);
			
			this.getProductService() .storeProductImage(productId, storedFileId);
			
			return null;
	    }

	@GetMapping(value = "/view")
	public void view(HttpServletResponse resp, String documentId) throws IOException {
		if (documentId == null || documentId.equals("null") || documentId.endsWith(".pdf")) {
			documentId = "dummy.jpg";
		}
		// byte[] data = storageService.read(documentId);
		// out.write(data);
		ServletOutputStream out = resp.getOutputStream();
		// resp.setContentType("application/pdf");
		service.read(out, documentId);

	}
}
